const db = wx.cloud.database()
const Time = require('../../utils/time/TimeUtil2')
const JF = require('../../utils/jifen/jifen')
const dbsk = wx.getStorageSync('autt')

Page({
  data: {
    today: Time.getRiQiObject(Time.getDangQianRiQi()), //今天
    riqi: Time.getRiQiObject(Time.getDangQianRiQi()),
    weekday: ["日", "一", "二", "三", "四", "五", "六"], //周几
    showemo: "none", //显示记录日期
    emoinges: '', //表情对象
    clockriqi: {}, //点击选择心情
    jilubutton: false, //记录心情按钮true是修改
    xiaoxiaotishi: '', //消息提示
    renwu: '', //任务提示
  },
  // 页面加载
  onLoad: function (options) {
    this.setData({
      user: {
        id: options.id,
        aut: options.aut
      }
    })
    this.ClearClockRiQi()
    this.getemoimges()
    this.getDangQianYueEmo(this.data.riqi.nian, this.data.riqi.yue)
    this.getdatabiues()
    this.getrenwua()
  },

  //查找任务页面
  async getrenwua() {
    let value = wx.getStorageSync('autt').user
    let a = await db.collection('xiangta').where({
      autid: value._id
    }).get()
    let data = a.data[0].dbarr
    let conts = 0;
    console.log(data);
    data.forEach((item, index) => {
      if (!item.zt) {
        conts++
      }
    })
    if (conts > 0) {
      let str = "有" + conts + "条新的任务"
      this.setData({
        renwu: str,
      })
    }
  },
  //页面加载完成显示
  onReady() {},
  //获取图片对象
  //给表情初始化样式
  initemostyle(aray) {
    aray.forEach(e => {
      e.imges['styley'] = ''
    });
    // console.log("执行玩成");
    return aray;
  },
  //获取心情图片页面
  async getemoimges() {
    const MAX_LIMIT = 20
    // 先取出集合记录总数
    const countResult = await db.collection('imgges').count()
    const total = countResult.total
    // 计算需分几次取
    const batchTimes = Math.ceil(total / 20)
    // 承载所有读操作的 promise 的数组
    const tasks = []
    for (let i = 0; i < batchTimes; i++) {
      const promise =  db.collection('imgges').skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
      tasks.push(promise)
    }
    let a = await (await Promise.all(tasks)).reduce((acc,cur)=>{
      return acc.data.concat(cur.data)
    })
    let bb = this.initemostyle(a)
    this.setData({
      emoinges: bb
    })
  },
  // 切换上下一个月
  shangyigeyue(e) {
    //1是上一个月2是下一个月
    let xz = e.currentTarget.dataset.qiehuan;
    let yue;
    let nian;
    if (xz == 1) {
      // 上个月
      yue = this.data.riqi.yue - 1
      nian = this.data.riqi.nian
      if (yue == 0) {
        nian = nian - 1
        yue = 12
      }
    } else {
      // 下个月
      yue = this.data.riqi.yue + 1
      nian = this.data.riqi.nian
      if (yue == 13) {
        nian = nian + 1
        yue = 1
      }
    }
    let data = {
      nian: nian,
      yue: yue
    }
    this.setData({
      riqi: Time.getRiQiObject(data, 1)
    })
    this.getDangQianYueEmo(this.data.riqi.nian, this.data.riqi.yue)
  },
  //点击日期设置心情
  settingemo(e) {
    //点击的内容对象
    let day = e.currentTarget.dataset.content;
    if (day != 88) {
      let emoimgid = day.emoimg_id; //数据库id
      let listid = day.list_id; //表情id
      let emotext //文本
      let index
      let style
      if (listid) {
        // 修改
        this.setData({
          jilubutton: true
        })
        emotext = day.emotext
        //根据id找到对应的图片
        let arr = this.data.emoinges
        for (let i = 0; i < arr.length; i++) {
          const e = arr[i];
          if (e._id === emoimgid) {
            e.imges.styley = 'xzemo';
            index = i
            style = e.imges.style
          }
        }
        this.setData({
          emoinges: arr
        })
      }

      // 获取当前年月日
      let year = this.data.riqi.nian;
      let more = this.data.riqi.yue;
      let d = day.riqi_id
      //选择心情
      this.setData({
        clockriqi: {
          nian: year,
          yue: more,
          ri: d,
          emotext: emotext ? emotext : '',
          listid: listid ? listid : this.data.clockriqi.listid,
          xzemo: emoimgid ? emoimgid : this.data.clockriqi.xzemo,
          styleemo: style ? style : this.data.clockriqi.styleemo,
          emoindex: index ? index : this.data.clockriqi.emoindex
        }
      })

      //显示心情页面
      this.showemo(1)

    }
  },
  // clock设置属性
  ClearClockRiQi() {
    this.setData({
      clockriqi: {
        nian: '',
        yue: '',
        ri: '',
        emotext: '',
        listid: '',
        xzemo: '',
        styleemo: '',
        emoindex: ''
      }
    })
  },



  // 关闭心情页面
  settemo() {
    //清空点击
    try {
      this.setData({
        jilubutton: false
      })
      let arr = this.data.emoinges
      for (let i = 0; i < arr.length; i++) {
        const e = arr[i];
        e.imges.styley = '';
      }
      let emoidex = this.data.clockriqi.emoindex
      let xinemo = this.data.emoinges
      xinemo[emoidex].imges.styley = ''
      console.log(xinemo);
      this.setData({
        emoinges: xinemo
      })
    } catch {

    }
    this.ClearClockRiQi()
    this.showemo(2)

  },
  //显示心情页面
  showemo(p) {
    if (p == 1) {
      this.setData({
        showemo: ''
      })
    } else {
      this.setData({
        showemo: 'none'
      })
    }
  },
  //根据月份获取表情
  getDangQianYueEmo(nian, yue) {
    let max = String(nian) + yue
    let min = String(nian) + yue
    let chaxun = db.command
    console.log(dbsk);
    db.collection(dbsk.sjk).where({
      // db.collection('xiaokaiemo').where({
      //查找suoyin数组中lte(小于等于)年+月+20 and(并且) get(大于等于)年+月+01的数数据
      suoyin: chaxun.lte(max + '20').and(chaxun.gte(min + '01'))
      // suoyin:'20241126'
    }).get().then(res => {
      // console.log(res); //获取查询对象
      // qiandata.push(res.data)
      this.xuanranyemian(res.data)
    })
    db.collection(dbsk.sjk).where({
      // db.collection('xiaokaiemo').where({
      //查找suoyin数组中lte(小于等于)年+月+20 and(并且) get(大于等于)年+月+01的数数据
      suoyin: chaxun.lte(max + '31').and(chaxun.gte(min + '21'))
    }).get().then(res => {
      // console.log(res); //获取查询对象
      // qiandata.push(res.data)
      this.xuanranyemian(res.data)
    })
  },
  //将数据库查询到的数据跟页面做结合
  xuanranyemian(arr) {
    //获取数组
    // console.log(arr);
    let brr = []
    const ast = this.data.riqi.dangqian
    ast.forEach(e => {
      for (let i = 0; i < arr.length; i++) {
        const ele = arr[i];
        let pd = ele.suoyin.slice(-2)
        pd = pd[0] == '0' ? pd[1] : pd
        if (pd == e.riqi_id) {
          e.style = ele.style
          e.emoimg_id = ele.emoid
          e.emotext = ele.emotext
          e.list_id = ele._id
        }
      }
    });
    wx.showToast({
      title: '稍等',
      icon: 'loading',
      duration: 1500,
      mask: true,
      success: this.dianwo()
    })
  },
  //点我渲染重新
  dianwo() {
    let a = this.data.riqi
    this.setData({
      xx: true,
      riqi: a
    })
  },
  // 点击选择心情
  xzemostyle(e) {
    let emo = e.currentTarget.dataset.content;
    let i = e.currentTarget.dataset.index;
    console.log(emo);
    let xinemo = this.data.emoinges[i]
    let xinarr = this.data.emoinges
    //清空选择
    // debugger
    if (xinemo.imges.styley == 'xzemo') {
      xinemo.imges.styley = ''
    } else {
      xinarr.forEach(e => {
        e.imges.styley = ''
      });
      xinemo.imges.styley = 'xzemo'
      xinarr[i] = xinemo
      // this.  updeatClockRiQi(year,more,d,tex,listid,xinemo._id,xinemo.imges.styke)
    }
    // console.log(xinarr);
    this.setData({
      emoinges: xinarr,
      clockriqi: {
        nian: this.data.clockriqi.nian,
        yue: this.data.clockriqi.yue,
        ri: this.data.clockriqi.ri,
        emotext: this.data.clockriqi.emotext,
        listid: this.data.clockriqi.listid,
        xzemo: emo._id,
        styleemo: emo.imges.style,
        emoindex: i,
      }
    })
  },
  //输入框失去焦点执行
  getemotext(e) {
    let xin = this.data.clockriqi
    xin.emotext = e.detail.value,
      this.setData({
        clockriqi: xin
      })
  },


  // 更新数据修改心情
  updateEom(emo, text, emostyle, aut) {
    let data = Time.formatDate(this.data.clockriqi)
    db.collection(dbsk.sjk).doc(this.data.clockriqi.listid).update({
      // db.collection('xiaokaiemo').doc(this.data.clockriqi.listid).update({
      data: {
        // 表示将 done 字段置为 true
        name: aut,
        emotext: text,
        emoid: emo,
        style: emostyle,
        data: data
      },
      success: function (res) {}
    })
    this.settemo()
  },


  //提交心情
  jilutext() {
    let emo = this.data.clockriqi
    let user = this.data.user //作者
    if (this.data.jilubutton) {
      this.updateEom(emo.xzemo, emo.emotext, emo.styleemo, user.aut)
      wx.showModal({
        title: '宝宝',
        content: '修改完成咯哟~',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定');
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      })
      this.getDangQianYueEmo(this.data.riqi.nian, this.data.riqi.yue)
    } else {
      if (user) {
        let tite = this.data.emoinges[emo.emoindex].tite //提示标题
        // console.log();
        this.tijiaoemo(emo.xzemo, emo.emotext, emo.styleemo, user.aut)
        wx.showModal({
          title: '宝宝',
          content: tite,
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定');
            } else if (res.cancel) {
              console.log('用户点击取消');
            }
          }
        })
        this.getDangQianYueEmo(this.data.riqi.nian, this.data.riqi.yue)
        //积分
        this.openDemJF(2, "签到积分")
      }
    }
    this.settemo()
  },

  //打包发给服务器
  //将获取的内容打包发给服务器 表情 文本 天数{年:月:日}
  tijiaoemo(emo, text, emostyle, aut) {
    let datat = new Date()
    let shijian = Time.formatDatetime(datat)
    // console.log(shijian);//当前时间
    let emoshijan = Time.formatDate(this.data.clockriqi)
    // console.log(emoshijan);//设置表情的时间
    let s = String(this.data.clockriqi.ri)
    let xinri = s.length == 1 ? ('0' + s) : s
    // let ss=String(this.data.clockriqi.yue)
    // let xinyue = ss.length == 1 ? ('0' + ss) : ss
    let suoyin = this.data.clockriqi.nian.toString() + (this.data.clockriqi.yue) + xinri
    //添加记录
    db.collection(dbsk.sjk).add({
      // db.collection('xiaokaiemo').add({
      data: {
        name: aut,
        emoid: emo, //表情样式id
        data: shijian, //当前的时间
        emodate: emoshijan, //记录表情的时间
        emotext: text, //小日记
        suoyin: suoyin, //索引格式化的天数20241123
        style: emostyle, //这个表情的样式
      },
      success: this.getDangQianYueEmo(this.data.riqi.nian, this.data.riqi.yue)
    })
    // 关闭表情显示框
    this.setData({
      showemo: 'none'
    })
  },



  // 更新数据
  updateEom(emo, text, emostyle, aut) {
    let data = Time.formatDate(this.data.clockriqi)
    db.collection(dbsk.sjk).doc(this.data.clockriqi.listid).update({
      // db.collection('xiaokaiemo').doc(this.data.clockriqi.listid).update({
      data: {
        // 表示将 done 字段置为 true
        name: aut,
        emotext: text,
        emoid: emo,
        style: emostyle,
        data: data
      },
      success: this.getDangQianYueEmo(this.data.riqi.nian, this.data.yue)
    })
    this.setData({
      showemo: 'none'
    })
  },

  // 加积分
  async openDemJF(num, string) {
    //连接数据库\
    let uup = db.command
    let tishi = '积分+' + num
    let bz = string + '+' + num
    const _ = db.command
    //获取当前时间
    let tim = Time.getDangQianRiQi()
    let datad = Time.formatDatetime(tim)
    let dx = {
      nr: bz,
      time: datad
    }
    let a = await db.collection('users').doc(this.data.user.id).get()
    a = a.data.jfmingxi
    // console.log(a);
    //获取本地数据
    // let ve = wx.getStorageSync('autt')
    // let arres = ve.user.jfmingxi
    // if (arres.length > 50) {
    //   arres = arres.slice(0, 50)
    // }
    a.unshift(dx)
    db.collection('users').doc(this.data.user.id).update({
      // data 传入需要局部更新的数据
      data: {
        jf: uup.inc(num),
        jfmingxi: a
      },
      success: function (res) {
        wx.showToast({
          title: tishi,
          num,
          icon: 'success',
          duration: 2000
        })
      }

    })
  },
  //查询数据库对方使用券的消息
  async getdatabiues() {
    var value = wx.getStorageSync('autt')
    let count = await db.collection(value.user.shangpin).where({
      df: true
    }).count()
    //{total: 9, errMsg: "collection.count:ok"}
    let a = count.total < 10 ? count.total : '好多好多好多'

    let str = '你有' + a + '条消息未处理'
    this.setData({
      xiaoxiaotishi: str
    })
    value.xiaoxi = count.total
    wx.setStorageSync('autt', value)
  },
})